package com.shuaiche.yeguan.net.http;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import org.apache.http.conn.ConnectTimeoutException;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import okhttp3.Headers;

/**
 * jsonarray 类型字符串解析
 */

public abstract class HttpArrayCallBack <T> implements CallBack{

    private Context mContext;
    Handler mHandler;
    private Class<?> cls;
    private boolean isArray = false;//返回数据是否为json数组
    private Gson gson;

    public HttpArrayCallBack(Context context) {
        mContext = context.getApplicationContext();
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void onStart() {

    }

    @Override
    public void onFinish() {

    }

    @Override
    public void onSuccess(String result) {

        if (TextUtils.isEmpty(result)){
            return;
        }
        if (!result.contains("[")){
            return;
        }
        gson = new Gson();
        cls = clazzInfo(this);
        parserJsonArray(result);
    }

    @Override
    public void onSuccess(String result, Headers headers) {

    }

    public void parserJsonArray(String strJson){
        try {
            final List<T> list = new ArrayList<>();
            JsonParser parser = new JsonParser();
            JsonElement el = parser.parse(strJson);
            JsonArray jsonArray = null;
            if(el.isJsonArray()){
                jsonArray = el.getAsJsonArray();
            }
            //遍历JsonArray对象
            Iterator it = jsonArray.iterator();
            while(it.hasNext()){
                JsonElement e = (JsonElement)it.next();
                T obj = (T) gson.fromJson(e, cls);
                list.add(obj);
            }
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    onSuccessed(list);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    @Override
    public void onFailure(final Exception e) {
        if (e != null){
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    String error = "请求异常";

                    if (e instanceof ConnectException) {// 不能在指定的ip和端口上建立连接
                        error = "无法和服务器建立连接";
                    } else if (e instanceof ConnectTimeoutException) {// 建立连接超时
                        error = "与服务器建立连接超时";
                    } else if (e instanceof SocketTimeoutException) {// 读取数据超时
                        error = "服务器读取数据超时";
                    } else if (e instanceof UnknownHostException) {
                        error = "网络异常";
                    } else if( e instanceof InterruptedIOException){
                        error = "网络连接失败";
                    }
                    else if(e instanceof IOException){
                        if(e.getLocalizedMessage().equals("Canceled")){
                            return;
                        }
                        error = "网络连接中断";
                    }
                    Toast.makeText(mContext,error,Toast.LENGTH_SHORT).show();
                    onFailured();
                }
            });
        }else {
            mHandler.post(new Runnable(){
                @Override
                public void run() {
                    onFailured();
                }
            });

        }
    }

    public abstract void onSuccessed(Object result);

    public abstract void onFailured();

    public static <T>Class<?> clazzInfo(Object obj){
        Type genType = obj.getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class<?>) params[0];

    }

}
